package com.zhihuichongcheng.application.ui.task;

import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Parcel;
import android.provider.MediaStore;
import android.support.v7.widget.LinearLayoutManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.GridLayout;
import android.widget.ImageView;
import android.widget.Toast;

import com.alibaba.sdk.android.oss.ClientException;
import com.alibaba.sdk.android.oss.ServiceException;
import com.alibaba.sdk.android.oss.callback.OSSCompletedCallback;
import com.alibaba.sdk.android.oss.callback.OSSProgressCallback;
import com.alibaba.sdk.android.oss.internal.OSSAsyncTask;
import com.alibaba.sdk.android.oss.model.ObjectMetadata;
import com.alibaba.sdk.android.oss.model.PutObjectRequest;
import com.alibaba.sdk.android.oss.model.PutObjectResult;
import com.bumptech.glide.Glide;
import com.jcodecraeer.xrecyclerview.XRecyclerView;
import com.smartlib.cmnObject.dialog.DialogOnClick;
import com.smartlib.cmnObject.util.DialogUtil;
import com.smartlib.cmnObject.util.GsonUtil;
import com.smartlib.cmnObject.util.StringUtil;
import com.smartlib.cmnObject.util.ToastOpt;
import com.zhihuichongcheng.application.R;
import com.zhihuichongcheng.application.base.BaseActivity;
import com.zhihuichongcheng.application.bean.cricle.CricleImageInfo;
import com.zhihuichongcheng.application.bean.mine.UserBean;
import com.zhihuichongcheng.application.bean.task.TaskBean;
import com.zhihuichongcheng.application.bean.task.TaskCommentBean;
import com.zhihuichongcheng.application.constant.Constants;
import com.zhihuichongcheng.application.constant.NetworkAPI;
import com.zhihuichongcheng.application.net.HttpCallback;
import com.zhihuichongcheng.application.net.HttpManager;
import com.zhihuichongcheng.application.ui.cricle.activity.ShowImageActivity;
import com.zhihuichongcheng.application.ui.im.activity.UserListActivity;
import com.zhihuichongcheng.application.ui.task.adapter.TaskContentAdapter;
import com.zhihuichongcheng.application.util.BroadCastUtils;
import com.zhihuichongcheng.application.util.CollectionUtils;
import com.zhihuichongcheng.application.util.StringUtils;
import com.zhihuichongcheng.application.widget.SuperEditText;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

import cn.finalteam.rxgalleryfinal.RxGalleryFinal;
import cn.finalteam.rxgalleryfinal.bean.MediaBean;
import cn.finalteam.rxgalleryfinal.imageloader.ImageLoaderType;
import cn.finalteam.rxgalleryfinal.rxbus.RxBusResultSubscriber;
import cn.finalteam.rxgalleryfinal.rxbus.event.ImageMultipleResultEvent;

import static com.zhihuichongcheng.application.constant.Constants.REQUESTCODE_CAPTURE_CAMEIA;

/**
 * TaskDetail Created by LK on 2017/1/9.
 */
public class TaskDetailActivity extends BaseActivity
        implements View.OnClickListener {
    public static final int REQUEST_CODE_RESET_TITLE = 1000;
    public static final int REQUEST_CODE_RESET_CONTENT = 1001;
    public static final int REQUEST_CODE_RESET_EXECUTOR = 1002;
    public static final int REQUEST_CODE_RESET_LOCATION = 1003;
    public static final int REQUEST_CODE_RESET_CC_USERS = 1004;
    public static final int REQUEST_CODE_RESET_SHOW_IMG = 1005;

    public static final String EXTRA_TASK_ID = "extra_task_id";
    protected HttpManager manager;
    protected Handler handler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            switch (msg.what) {
            }
        }
    };
    private int currentTaskId;
    private XRecyclerView mRecyclerView;
    private TaskContentAdapter mAdapter;
    //创建评论相关
    private View commentLayout;
    private ImageView mBtnChooseImg;
    private SuperEditText mInputComment;
    private Button mBtnSendComment;
    private String mUpdateIconCameraPath;
    private GridLayout mImgGridLayout;
    //    private List<Object> mInputImgs = new ArrayList<>();
    private Map<MediaBean, String> mInputImgs = new LinkedHashMap<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //接收参数
        if (null != getIntent().getExtras()) {
            Bundle bundle = getIntent().getExtras();
            if (bundle.containsKey(EXTRA_TASK_ID))
                currentTaskId = bundle.getInt(EXTRA_TASK_ID);
        }
        setContentView(R.layout.activity_create_task);
        manager = HttpManager.getInstance(this);
        initView();
        initListView();
        setDataToViews();
    }

    private void initView() {
        setTitle("任务");
        getTvArrowTitle().setVisibility(View.INVISIBLE);

        mRecyclerView = (XRecyclerView) this.findViewById(R.id.rv_task);
        mRecyclerView.setHasFixedSize(true);

        commentLayout = this.findViewById(R.id.comment_layout);
        mBtnChooseImg = (ImageView) this.findViewById(R.id.btn_choose_img);
        mInputComment = (SuperEditText) this.findViewById(R.id.input_comment);
        mInputComment.setTaskId(currentTaskId);
        mBtnSendComment = (Button) this.findViewById(R.id.btn_send_comment);
        mImgGridLayout = (GridLayout) this.findViewById(R.id.task_input_img_layout);

        mBtnChooseImg.setOnClickListener(this);
        mBtnSendComment.setOnClickListener(this);
    }

    /**
     * 发布任务
     */
    private void save() {
        DialogUtil.showLoadDiadlog(getContext());
        TaskBean taskbean = mAdapter.getTaskBean();
        HashMap<String, String> params = new HashMap<>();
        if (taskbean.getTaskId() > 0) {
            params.put("userMissionId", taskbean.getTaskId() + "");
        }
        params.put("type", taskbean.getType() + "");
        params.put("name", taskbean.getTitle());
        params.put("receiveUserId", taskbean.getExecutorUserIds());
        params.put("finishTime", taskbean.getFinishTimeFormat());
        params.put("priority", taskbean.getPriority() + "");
        params.put("token", mUser.getToken());

        params.put("location", taskbean.getLocation());
        params.put("content", taskbean.getContent());
        params.put("copyUserId", taskbean.getCCUserUserIds());
        manager.post(NetworkAPI.MISSION_PUBLISH, new HttpCallback() {
            @Override
            public void onSuccess(int code, String value, String msg) {
                DialogUtil.dismiss(getContext());
                if (code == 2) {
                    ToastOpt.createToast(getContext(), msg);
                    return;
                }
                ToastOpt.createToast(getContext(), "发布成功");
                BroadCastUtils.getInstance().actionRefreshTaskList(TaskDetailActivity.this);
                finish();
            }

            @Override
            public void onFailure(String value) {
                ToastOpt.createToast(getContext(), "发布失败 " + value);
            }
        }, params);
    }

    /**
     * 检查必填项
     */
    private String checkItems() {
        TaskBean taskbean = mAdapter.getTaskBean();
        if (taskbean.getType() <= 0)
            return "请设置任务类型";
        if (StringUtils.isEmpty(taskbean.getTitle()))
            return "请设置任务名称";
        if (StringUtils.isEmpty(taskbean.getExecutorNicknames()))
            return "请设置执行者";
        if (StringUtils.isEmpty(taskbean.getDate()))
            return "请设置截止日期";
        if (StringUtils.isEmpty(taskbean.getTime()))
            return "请设置截止时间";
        return null;
    }

    private void initListView() {
        LinearLayoutManager manager = new LinearLayoutManager(getContext());
        manager.setOrientation(LinearLayoutManager.VERTICAL);
        mRecyclerView.setLayoutManager(manager);
        mAdapter = new TaskContentAdapter(this);
        mRecyclerView.setAdapter(mAdapter);
        mRecyclerView.setLoadingMoreEnabled(false);
        if (createTask()) {
            mRecyclerView.setPullRefreshEnabled(false);
        } else {
            mRecyclerView.setLoadingListener(new XRecyclerView.LoadingListener() {
                @Override
                public void onRefresh() {
                    requestTaskDetail();
                }

                @Override
                public void onLoadMore() {
                }
            });
        }
    }

    private boolean createTask() {
        return currentTaskId <= 0;
    }

    private void setDataToViews() {
        if (createTask())
            loadViewToCreateTask();
        else
            loadViewToReadTask();
        showCommentLayout(!createTask());
    }

    private void showCommentLayout(boolean b) {
        commentLayout.setVisibility(b ? View.VISIBLE : View.GONE);
    }

    private void loadViewToReadTask() {
        requestTaskDetail();
    }

    private void requestTaskDetail() {
        DialogUtil.showLoadDiadlog(getContext());
        HashMap<String, String> params = new HashMap<>();
        params.put("userMissionId", currentTaskId + "");
        params.put("token", mUser.getToken());
        manager.post(NetworkAPI.MISSION_DETAIL, new HttpCallback() {
            @Override
            public void onSuccess(int code, String value, String msg) {
                DialogUtil.dismiss(getContext());
                if (code == 2) {
                    ToastOpt.createToast(getContext(), msg);
                    return;
                }
                TaskBean task = GsonUtil.praseFromStringToBean(value, TaskBean.class);
                mAdapter.setTaskBean(task);
                mAdapter.notifyDataSetChanged();
                loadComment(false);

                if (currentTaskId > 0 && task.getCreateUserId() == Integer.parseInt(app.getUser().getUserId())) {
                    setTvRight("保存", new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            String checkResult = checkItems();
                            if (StringUtil.isEmpty(checkResult))
                                save();
                            else
                                ToastOpt.createToast(getContext(), checkResult);
                        }
                    });
                    setTvRight2("关闭", new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            closeTask();
                        }
                    });
                }

            }

            @Override
            public void onFailure(String value) {
                DialogUtil.dismiss(getContext());
            }
        }, params);
    }

    private void loadViewToCreateTask() {
        setTvRight("保存", new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String checkResult = checkItems();
                if (StringUtil.isEmpty(checkResult))
                    save();
                else
                    ToastOpt.createToast(getContext(), checkResult);
            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_choose_img:
                DialogUtil.showUploadFile(mContext, new DialogOnClick<String>() {
                    @Override
                    public void onClick(String s) {
                        getImageFromCamera();
                    }
                }, new DialogOnClick<String>() {
                    @Override
                    public void onClick(String s) {
                        selectImageFromAlbum();
                    }
                });
                break;
            case R.id.btn_send_comment:
                sendComment();
                break;
        }
    }

    /**
     * 发送评论
     */
    private void sendComment() {
        if (StringUtils.isEmpty(mInputComment.getText().toString().trim())) {
            ToastOpt.createToast(getContext(), "请填写评论内容");
            return;
        }
        if (checkImg()) {
            DialogUtil.showLoadDiadlog(mContext);
            HashMap<String, String> paramsDemo = new HashMap<>();
            paramsDemo.put("token", mUser.getToken());
            paramsDemo.put("userMissionId", currentTaskId + "");
            paramsDemo.put("content", mInputComment.getText().toString().trim());
            if (!StringUtils.isEmpty(mInputComment.getAtUserIds())) {
                paramsDemo.put("atUserId", mInputComment.getAtUserIds());
            }
            final String[] imgUrls = {""};
            CollectionUtils.iterator(mInputImgs, new CollectionUtils.AIIteratorMapCallBack() {
                @Override
                public boolean callback(Object key, Object value, int position) {
                    MediaBean itemBean = (MediaBean) key;
                    String imgUrl = value.toString().trim();
                    imgUrls[0] += imgUrl + ",";
                    return false;
                }
            });
            if (!StringUtils.isEmpty(imgUrls[0]))
                paramsDemo.put("image", imgUrls[0]);
            manager.post(NetworkAPI.MISSION_COMMENT_PUBLISH, new HttpCallback() {
                @Override
                public void onSuccess(int code, String value, String msg) {
                    DialogUtil.dismiss(getContext());
                    if (code == 2) {
                        ToastOpt.createToast(getContext(), msg);
                        return;
                    }
                    ToastOpt.createToast(getContext(), "发布成功");
                    loadComment(true);
                    mInputComment.setText("");
                    mInputImgs.clear();
                    mImgGridLayout.removeAllViews();
                }

                @Override
                public void onFailure(String value) {
                    ToastOpt.createToast(getContext(), "发布失败 " + value);
                    DialogUtil.dismiss(getContext());
                }
            }, paramsDemo);
        } else {
            postCommentImgs();
        }
    }

    private void postCommentImgs() {
        CollectionUtils.iterator(mInputImgs, new CollectionUtils.AIIteratorMapCallBack() {
            @Override
            public boolean callback(Object key, Object value, int position) {
                if (StringUtils.isEmpty(value + "")) {
                    MediaBean bean = (MediaBean) key;
                    updateOss(bean, ((MediaBean) key).getOriginalPath());
                }
                return false;
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE_RESET_TITLE) {
            if (resultCode == EXTRA_RESPONSE_CODE_SUCCESS) {
                String title = data.getStringExtra(ContentEditActivity.EXTRA_RESULT);
                mAdapter.notifyTaskTitle(title);
            }
        } else if (requestCode == REQUEST_CODE_RESET_CONTENT) {
            if (resultCode == EXTRA_RESPONSE_CODE_SUCCESS) {
                String content = data.getStringExtra(ContentEditActivity.EXTRA_RESULT);
                mAdapter.notifyTaskContent(content);
            }
        } else if (requestCode == REQUEST_CODE_RESET_LOCATION) {
            if (resultCode == EXTRA_RESPONSE_CODE_SUCCESS) {
                String location = data.getStringExtra(ContentEditActivity.EXTRA_RESULT);
                mAdapter.notifyTaskLocation(location);
            }
        } else if (requestCode == REQUEST_CODE_RESET_EXECUTOR) {
            if (resultCode == EXTRA_RESPONSE_CODE_SUCCESS) {
                List<UserBean> result = data.getParcelableArrayListExtra(UserListActivity.EXTRA_RESULT_USERS);
                mAdapter.notifyExecutors(result);
            }
        } else if (requestCode == REQUEST_CODE_RESET_CC_USERS) {
            if (resultCode == EXTRA_RESPONSE_CODE_SUCCESS) {
                List<UserBean> result = data.getParcelableArrayListExtra(UserListActivity.EXTRA_RESULT_USERS);
                mAdapter.notifyCCUsers(result);
            }
        } else if (requestCode == REQUESTCODE_CAPTURE_CAMEIA) {
            //相机选取图片
            if (resultCode == Activity.RESULT_OK) {
                Uri uri = Uri.fromFile(new File(mUpdateIconCameraPath));
                MediaBean mediaBean = new MediaBean();
                mediaBean.setOriginalPath(uri.getPath());
                mInputImgs.put(mediaBean, "");
                setImgToInputLayout();
            }
        } else if (requestCode == REQUEST_CODE_RESET_SHOW_IMG) {
            if (resultCode == RESULT_OK) {
                if (data.hasExtra(ShowImageActivity.EXTRA_RESULT_IMGS)) {
                    final ArrayList<CricleImageInfo> imgs = data.getParcelableArrayListExtra(ShowImageActivity.EXTRA_RESULT_IMGS);
                    if (null == imgs) {
                        mInputImgs.clear();
                    } else {
                        final Map<MediaBean, String> delImgs = new LinkedHashMap<>();
                        CollectionUtils.iterator(mInputImgs, new CollectionUtils.AIIteratorMapCallBack() {
                            @Override
                            public boolean callback(final Object key, final Object value, int position) {
                                final MediaBean itemBean = (MediaBean) key;
                                CollectionUtils.iterator(imgs, new CollectionUtils.AIIteratorListCallBack() {
                                    @Override
                                    public boolean callback(Object data, int position) {
                                        if (((CricleImageInfo) data).getJinbaoHomeImgUrl().equals(itemBean.getOriginalPath())) {
                                            delImgs.put((MediaBean) key, (String) value);
                                        }
                                        return false;
                                    }
                                });
                                return false;
                            }
                        });
                        mInputImgs.clear();
                        mInputImgs.putAll(delImgs);
                    }
                    setImgToInputLayout();
                }
            }
        }
    }

    /**
     * 加载评论
     */
    private void loadComment(final boolean scrollToBottom) {
        TaskBean taskbean = mAdapter.getTaskBean();
        HashMap<String, String> params = new HashMap<>();
        if (taskbean.getTaskId() > 0) {
            params.put("userMissionId", taskbean.getTaskId() + "");
        }
        params.put("token", mUser.getToken());
        DialogUtil.showLoadDiadlog(getContext());
        manager.post(NetworkAPI.MISSION_COMMENT_LIST, new HttpCallback() {
            @Override
            public void onSuccess(int code, String value, String msg) {
                DialogUtil.dismiss(getContext());
                if (code == 2) {
                    ToastOpt.createToast(getContext(), msg);
                    return;
                }
                List<TaskCommentBean> beanList = GsonUtil.paraeFromStringToList(value, TaskCommentBean.class);
                mAdapter.reSetTaskCommentList(beanList);
                mAdapter.notifyDataSetChanged();
                mRecyclerView.loadMoreComplete();
                mRecyclerView.loadMoreComplete();
                mRecyclerView.refreshComplete();
                if (scrollToBottom)
                    mRecyclerView.smoothScrollToPosition(mAdapter.getItemCount());
            }

            @Override
            public void onFailure(String value) {
                mRecyclerView.loadMoreComplete();
                DialogUtil.dismiss(getContext());
                mRecyclerView.loadMoreComplete();
                mRecyclerView.refreshComplete();
            }
        }, params);

    }

    /***
     * 拍照
     */
    private void getImageFromCamera() {
        if (mInputImgs.size() > 8) {
            ToastOpt.createToast(getContext(), "图片已达上限");
            return;
        }
        String state = Environment.getExternalStorageState();
        mUpdateIconCameraPath = Constants.Const_Cache_Dir + System.currentTimeMillis() + ".png";
        if (state.equals(Environment.MEDIA_MOUNTED)) {
            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            File dir = new File(Constants.Const_Cache_Dir);
            if (!dir.exists()) {
                dir.mkdirs();
            }
            File f = new File(mUpdateIconCameraPath);//localTempImgDir和localTempImageFileName是自己定义的名字
            Uri u = Uri.fromFile(f);
            intent.putExtra(MediaStore.Images.Media.ORIENTATION, 0);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, u);
            startActivityForResult(intent, REQUESTCODE_CAPTURE_CAMEIA);
        } else {
            Toast.makeText(mContext, "请确认已经插入SD卡", Toast.LENGTH_LONG).show();
        }
    }

    /***
     * 从相册选择
     */
    private void selectImageFromAlbum() {
        if (mInputImgs.size() > 8) {
            ToastOpt.createToast(getContext(), "图片已达上限");
            return;
        }
        RxGalleryFinal
                .with(getContext())
                .image()
                .radio()
                .multiple()
                .maxSize(9)
                .imageLoader(ImageLoaderType.GLIDE)
                .selected(CollectionUtils.getKeyList(mInputImgs))
                .subscribe(new RxBusResultSubscriber<ImageMultipleResultEvent>() {
                    @Override
                    protected void onEvent(ImageMultipleResultEvent baseResultEvent) throws Exception {
                        ImageMultipleResultEvent event = baseResultEvent;
                        List<MediaBean> result = baseResultEvent.getResult();
                        mInputImgs.clear();
                        for (int i = 0; i < result.size(); i++) {
                            mInputImgs.put(result.get(i), "");
                        }
                        setImgToInputLayout();
                    }
                })
                .openGallery();
    }


    private String getRealPathFromURI(Uri contentUri) { //传入图片uri地址
        String path = "";
        Cursor cursor = mContext.getContentResolver().query(contentUri, null, null, null, null);
        if (cursor != null) {
            cursor.moveToFirst();
            String document_id = cursor.getString(0);
            document_id = document_id.substring(document_id.lastIndexOf(":") + 1);
            cursor.close();
            cursor = mContext.getContentResolver().query(
                    android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                    null, MediaStore.Images.Media._ID + " = ? ", new String[]{document_id}, null);
            if (cursor != null) {
                cursor.moveToFirst();
                path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
                cursor.close();
            }
        }
        return path;
    }

    private void setImgToInputLayout() {
        mImgGridLayout.removeAllViews();
        CollectionUtils.iterator(mInputImgs, new CollectionUtils.AIIteratorMapCallBack() {
            @Override
            public boolean callback(final Object key, Object value, final int position) {
                MediaBean mediaBean = (MediaBean) key;
                ImageView itemView = (ImageView) LayoutInflater.from(mImgGridLayout.getContext()).
                        inflate(R.layout.view_comment_edit_img, mImgGridLayout, false);
                itemView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        showImages(position);
                    }
                });
                itemView.setOnLongClickListener(new View.OnLongClickListener() {
                    @Override
                    public boolean onLongClick(View view) {
                        DialogUtil.showSimpleAlertDialog(getContext(), new DialogOnClick() {
                            @Override
                            public void onClick(Object o) {
                                mInputImgs.remove(key);
                                setImgToInputLayout();
                            }
                        }, "删除图片");
                        return true;
                    }
                });
                Glide.with(getContext()).load(mediaBean.getOriginalPath()).into(itemView);
                mImgGridLayout.addView(itemView);
                return false;
            }
        });
    }

    private void showImages(int position) {
        final ArrayList<CricleImageInfo> images = new ArrayList<>();
        List<MediaBean> urlList = CollectionUtils.getKeyList(mInputImgs);
        CollectionUtils.iterator(urlList, new CollectionUtils.AIIteratorListCallBack() {
            @Override
            public boolean callback(Object data, int position) {
                Parcel parcel = Parcel.obtain();
                parcel.writeString(((MediaBean) data).getOriginalPath().trim().trim());
                CricleImageInfo cricleImageInfo = new CricleImageInfo(parcel);
                cricleImageInfo.setJinbaoHomeImgUrl(((MediaBean) data).getOriginalPath().trim().trim());
                images.add(cricleImageInfo);
                return false;
            }
        });
        Bundle bundle = new Bundle();
        bundle.putInt("index", position);
        bundle.putParcelableArrayList("list", images);
        bundle.putBoolean(ShowImageActivity.EXTRA_BOOLEAN_SHOW_DEL_BTN, true);
        startActivityForResult(ShowImageActivity.class, REQUEST_CODE_RESET_SHOW_IMG, bundle);
    }

    private void updateOss(final MediaBean bean, final String path) {
        mUser = app.getUser();
        if (mUser == null) {
            ToastOpt.createToast(mContext, "请先登陆");
            return;
        }
        DialogUtil.showLoadDiadlog(mContext);
        // 指定数据类型，没有指定会自动根据后缀名判断
        new Thread(new Runnable() {
            @Override
            public void run() {
                ObjectMetadata objectMeta = new ObjectMetadata();
                objectMeta.setContentType("image/jpeg");
                Random random = new Random(1000);//指定种子数字
                final String name = System.currentTimeMillis() + random.nextInt() + ".png";
                // 构造上传请求
                PutObjectRequest put = new PutObjectRequest("yirimao", name, path);
                put.setMetadata(objectMeta);
                try {
                    PutObjectResult putObjectResult = app.getOss().putObject(put);
                } catch (ClientException
                        e) {
                    e.printStackTrace();
                } catch (ServiceException e) {
                    e.printStackTrace();
                }

                // 异步上传时可以设置进度回调
                put.setProgressCallback(new OSSProgressCallback<PutObjectRequest>() {
                    @Override
                    public void onProgress(PutObjectRequest request, long currentSize, long totalSize) {
                        // 在这里可以实现进度条展现功能
                        Log.d("PutObject", "currentSize: " + currentSize + " totalSize: " + totalSize);
                    }
                });
                OSSAsyncTask task = app.getOss().asyncPutObject(put, new OSSCompletedCallback<PutObjectRequest, PutObjectResult>() {
                    @Override
                    public void onSuccess(PutObjectRequest request, PutObjectResult result) {
                        String imgUrl = Constants.OSS_ENDPOINT + "/" + name;
                        mInputImgs.put(bean, imgUrl);
                        if (checkImg())
                            sendComment();
                        DialogUtil.dismiss(getContext());
                    }

                    @Override
                    public void onFailure(PutObjectRequest request, ClientException clientExcepion, ServiceException serviceException) {
                        // 请求异常
                        ToastOpt.createToast(getContext(), "图片上传失败");
                        DialogUtil.dismiss(getContext());
                    }
                });
            }
        }).start();

    }

    private boolean checkImg() {
        final boolean[] flag = {true};
        CollectionUtils.iterator(mInputImgs, new CollectionUtils.AIIteratorMapCallBack() {
            @Override
            public boolean callback(Object key, Object value, int position) {
                if (StringUtils.isEmpty(value.toString())) {
                    flag[0] = false;
                    return true;
                }
                return false;
            }
        });

        return flag[0];
    }


    private void closeTask() {
        DialogUtil.showSimpleAlertDialog(getContext(), new DialogOnClick() {
            @Override
            public void onClick(Object o) {
                DialogUtil.showLoadDiadlog(getContext());
                HashMap<String, String> paramsDemo = new HashMap<>();
                paramsDemo.put("token", mUser.getToken());
                paramsDemo.put("userMissionId", currentTaskId + "");
                manager.post(NetworkAPI.MISSION_FINISH, new HttpCallback() {
                    @Override
                    public void onSuccess(int code, String value, String msg) {
                        DialogUtil.dismiss(getContext());
                        if (code == 2) {
                            ToastOpt.createToast(getContext(), msg);
                            return;
                        }
                        BroadCastUtils.getInstance().actionRefreshTaskList(getContext());
                        finish();
                    }

                    @Override
                    public void onFailure(String value) {
                        ToastOpt.createToast(getContext(), "关闭失败 " + value);
                        DialogUtil.dismiss(getContext());
                    }
                }, paramsDemo);
            }
        }, "确定关闭");
    }

}